package com.example.algorithm.queue;

/**
 * 双端队列
 */
public class Deque<E> {

    private E[] data;
    private int capacity, size, front, tail;

    public Deque() {
        this(10);
    }

    public Deque(int capacity) {
        data = (E[]) new Object[capacity];
        this.capacity = capacity;
        this.size = 0;
        this.front = 0;
        this.tail = 0;
    }

    public int getCapacity() {
        return this.capacity;
    }

    public int getSize() {
        return this.size;
    }

    public boolean isEmpty() {
        return this.size == 0;
    }

    /**
     * 与普通队列的 enqueue 方法逻辑一致，在队尾添加元素 tail 正常往前推进即可
     *
     * @param e
     */
    public void addLast(E e) {
        if (size == getCapacity()) {
            resize(getCapacity() * 2);
        }
        data[tail] = e;
        tail = (tail + 1) % getCapacity();
        size++;
    }

    /**
     * 在对首添加元素，
     * 此时 front 需要往后退，需要考虑特殊情况，当 front 已经是数组第一个位置时，往后退即是数组最后一个位置
     *
     * @param e
     */
    public void addFront(E e) {
        if (size == getCapacity()) {
            resize(getCapacity() * 2);
        }
        front = front == 0 ? getCapacity() - 1 : front - 1;
        data[front] = e;
        size++;
    }

    /**
     * 从队尾移除，此时 tail 需要往后退，需要考虑特殊情况，当 tail 已经是数组第一个位置时，往后退则是数组的最后一个位置
     *
     * @return
     */
    public E removeLast() {
        E ret = data[tail];
        data[tail] = null;
        tail = tail == 0 ? getCapacity() - 1 : tail - 1;
        size--;
        if (size == getCapacity() / 4 && getCapacity() / 2 != 0) {
            resize(getCapacity() / 2);
        }
        return ret;
    }

    /**
     * 与普通队列的dequeue方法逻辑一致
     * front 往前推进即可
     *
     * @return
     */
    public E removeFront() {
        E ret = data[front];
        data[front] = null;
        front = (front + 1) % getCapacity();
        size--;
        if (size == getCapacity() / 4 && getCapacity() / 2 != 0) {
            resize(getCapacity() / 2);
        }
        return ret;
    }

    private void resize(int newCapacity) {
        E[] newData = (E[]) new Object[newCapacity];
        for (int i = 0; i < size; i++) {
            newData[i] = this.data[(i + front) % getCapacity()];
        }
        data = newData;
        front = 0;
        tail = size;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(String.format("Queue: size = %d, capacity=%d\n", getSize(), getCapacity()));
        sb.append("front [");
        for (int i = 0; i < getSize(); i++) {
            sb.append(data[(i + front) % data.length]);
            if (i != getSize() - 1) {
                sb.append(", ");
            }
        }
        sb.append("] tail");
        return sb.toString();
    }

}
